<?
require_once('../config.php');
require_once(LIB.'/class_Template.php');
require_once(LIB.'/class_User.php');
require_once(LIB.'/class_Group.php');
require_once(LIB.'/class_Modules.php');
require_once(LIB.'/common_functions.php');
require_once(WEBSITE_ROOT.'/common/init.php');
require_once(MODULE_ROOT.'/modules.php');
define('DEFAULT_MODULE','admin_users');
define('DEFAULT_ACTION','index');

global $_modules;
$user_name=SESSION_value('user_name','');
$user_id=SESSION_value('user_id',0);
$module=GET_value('m',DEFAULT_MODULE);
$action=GET_value('a',DEFAULT_ACTION);

if ($user_id){
    $r = User :: get_user_data($user_id);
    if($r['success']){
        $u=$r['data'];
        $group_id = $u['group_id'];    
    }else{
        $group_id = 0;    
    }
}else{
    $group_id = 0;
}

//Call a special module to handle error
require_once MODULE_ROOT."/error/error_controller.php"; // Module error
$error_controller = new error_controller();

//Check if module controller file exist
$controller_file=MODULE_ROOT."/$module/".$module."_controller.php";
if (!file_exists($controller_file)){
    $error_controller -> set_error("Module <strong>$module</strong> not found!!");
    $error_controller -> fatality();
}else{
    require_once $controller_file;
    $controller_class = $module."_controller";
    $controller = new $controller_class();    
    $controller_action = "exec_".$action;
    if (method_exists($controller,$controller_action)){
        //Should implement checking authority here!
        $access = Group :: check_permission($group_id, $module, $action);
        if ($access || 'root'==$user_name){
            $t1=  get_micro_time();
            $view_data = $controller -> $controller_action();
            $exec_time=  get_micro_time()-$t1;
            $view_data['exec_time'] = sprintf('%8.6f',$exec_time);
        }else{
            $error_controller -> set_error("You have no permission to access!");
            $error_controller -> fatality();
        }
    }
    else
    {
        $error_controller -> set_error("Action $action not found!");
        $error_controller -> fatality();
    }
}    

if ($error_controller->is_fatality()){
    $view_data = $error_controller -> exec_error();
}

$layout_tpl = new Template('themes/main.html');
$layout_tpl -> set('view', $view_data);
$layout_tpl -> set('m', $module);
echo $layout_tpl->fetch();